package com.zhao.dota.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhao.dota.model.Permission;
import com.zhao.dota.service.PermissionService;
import com.zhao.dota.struct.Result;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/permission")
public class PermissionController {

    @Resource
    private PermissionService permissionService;

    @GetMapping("/")
    public Result<Page<Permission>> page(Page<Permission> page) {
        page = permissionService.page(page);
        return Result.success(page);
    }

    @GetMapping("/all")
    public Result<List<Permission>> all() throws Exception {
        List<Permission> list = permissionService.tree();
        return Result.success(list);
    }

    @GetMapping("/{id}")
    public Result<Permission> detail(@PathVariable Integer id) {
        Permission permission = permissionService.getById(id);
        return Result.success(permission);
    }

    @PostMapping("/")
    public Result<Permission> save(Permission permission) {
        if (permission.getMenu() == null) {
            permission.setMenu(false);
        }
        boolean b = permissionService.saveOrUpdate(permission);
        if (b) {
            return Result.success(permission);
        }
        return Result.error();
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Integer id) {
        boolean b = permissionService.removeById(id);
        return Result.complete(b);
    }

    @GetMapping("/rolePermissions")
    public Result<Map<String, Object>> rolePermissions(Integer roleId) {
        Map<String, Object> result = new HashMap<>();
        List<Permission> tree = permissionService.tree();
        List<Permission> checked = permissionService.rolePermissions(roleId);
        List<Integer> checkedList = checked.stream().map(Permission::getId).collect(Collectors.toList());
        result.put("tree", tree);
        result.put("checked", checkedList);
        return Result.success(result);
    }

    @PostMapping("/rolePermissions")
    public Result<Integer> saveRolePermissions(Integer roleId, Integer[] permissions) {
        int i = permissionService.saveRolePermissions(roleId, permissions);
        return Result.success(i);
    }

}
